﻿using FreeOPC.Config;
using FreeOPC.Server.MQTTService;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace FreeOPC.Server.Window
{
    public static class ServiceLocator
    {
        public static IServiceProvider instance { get; set; }
    }
    public class Startup
    {
        /// <summary>
        /// The service name.
        /// </summary>
        private readonly AssemblyName serviceName = Assembly.GetExecutingAssembly().GetName();

        /// <summary>
        /// Gets the MQTT service configuration.
        /// </summary>
        private readonly MqttConfiguration mqttServiceConfiguration = new();

        /// <summary>
        /// Initializes a new instance of the <see cref="Startup"/> class.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        public Startup(IConfiguration configuration)
        {
            configuration.GetSection("OPCMqttServer").Bind(this.mqttServiceConfiguration);
        }

        /// <summary>
        /// Configures the services.
        /// </summary>
        /// <param name="services">The services.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();

            services.AddSingleton(this.mqttServiceConfiguration);

            services.AddMvc().AddRazorPagesOptions(options => { options.RootDirectory = "/"; })
                .AddDataAnnotationsLocalization();

            // Workaround to have a hosted background service available by DI.
            services.AddSingleton(_ => new MqttService(this.mqttServiceConfiguration, "OPCMqttServer"));
            services.AddSingleton<IHostedService>(p => p.GetRequiredService<MqttService>());
            ServiceLocator.instance = services.BuildServiceProvider();


        }

        /// <summary>
        /// This method gets called by the runtime.
        /// </summary>
        /// <param name="app">The application.</param>
        /// <param name="env">The web hosting environment.</param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseSerilogRequestLogging();
            app.UseRouting();
            app.UseCors("any");
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "api/{controller=Home}/{action=Index}/{id?}");

            });
            _ = app.ApplicationServices.GetService<MqttService>();
        }
    }
}
